#pragma once

#include <functional>
#include <iostream>
#include <sys/types.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "InerAddr.hpp"
#include "ThreadPool.hpp"

using namespace ThreadPoolModule;

using func_t = std::function<void(int sockfd, const std::string&, InerAddr&)>;

const int defaultfd = -1;

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func)
        : _port(port), _sockfd(defaultfd), _is_running(false), _func(func)
    {

    }

    void Init()
    {
        // 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "create socket failed";
            return;
        }
        LOG(LogLevel::INFO) << "create socket success, sockfd: " << _sockfd;

        // 2. 绑定socket信息，ip和端口
        // 2.1 填充socdaddr_in结构体
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;

        // 2.1.1 转换ip地址为网络字节序
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());
        // 2.1.1 绑定到任何一个本地地址
        local.sin_addr.s_addr = INADDR_ANY;
        // 2.1.2 转换端口为网络字节序
        local.sin_port = htons(_port);

        // InerAddr addr("0", _port);
        // addr.NetAddr();

        // 2.2 绑定socket
        // 为什么服务器端需要显示的bind呢？IP和端口必须是众所周知且不能轻易改变的。
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "bind socket failed";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind socket success" << " port: " << _port;
    }

    void Start()
    {
        _is_running = true;
        // 大部分的软件都是死循环
        while(_is_running)
        {
            char buffer[1024] = {0};
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 1. 接收数据
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
            if(s > 0)
            {
                InerAddr client(peer);

                buffer[s] = 0;

                _func(_sockfd, buffer, client);
                // LOG(LogLevel::DEBUG) << "[" << peer_ip << ":" << peer_port << "]# " << buffer; // 1. 消息内容 2. 谁发的？

                // std::string echo_string = "server echo@ ";
                // echo_string += buffer;
                // 2. 发送数据
                // sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr*)&peer, len);
            }
        }
    }

    ~UdpServer()
    {
    }

private:
    int _sockfd;
    uint16_t _port;
    // std::string _ip;
    bool _is_running;
    func_t _func; // 服务器的回调函数，对数据进行处理
};
